package Controllers;

import Information.UserInfo;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import java.io.*;

import java.net.URL;
import java.util.ResourceBundle;

public class LoginController extends Application implements Initializable {
    @FXML
    private Button login; //登录
    @FXML
    private Button signUp; //注册账号
    @FXML
    private Button forgetPassword; //忘记密码
    @FXML
    private CheckBox rememberPassword; //记住密码
    @FXML
    private TextField ID; //账号
    @FXML
    private PasswordField password; //密码
    @FXML
    private AnchorPane Login_fxml; //登录界面

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //取用户登录历史账号
        File IDHistoryfile = new File("src/Passwords/UserIDHistory.txt");
        if (IDHistoryfile.exists()) {
            FileReader FR = null;
            try {
                FR = new FileReader("src/Passwords/UserIDHistory.txt");
                BufferedReader ID_reader = new BufferedReader(FR);
                String HistoryID = ID_reader.readLine();
                FR.close();
                ID.setText(HistoryID);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //取用户登录历史密码
        File PasswordHistoryfile = new File("src/Passwords/UserPasswordHistory.txt");
        if (PasswordHistoryfile.exists()) {
            FileReader fr = null;
            try {
                fr = new FileReader("src/Passwords/UserPasswordHistory.txt");
                BufferedReader Password_reader = new BufferedReader(fr);
                String HistoryPassword = Password_reader.readLine();
                fr.close();
                password.setText(HistoryPassword);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 初始化【记住密码】状态
        if(PasswordHistoryfile.length() != 0){
            rememberPassword.setSelected(true);
        }
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        try {
            AnchorPane root = FXMLLoader.load(getClass().getResource("/Resources/Login.fxml"));
            Scene scene = new Scene(root, 288.0, 400.0);
            //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.getIcons().add(new Image("/Images/logoblue.png"));
            primaryStage.setTitle("登录");

            // 调整窗体style实现隐藏标题栏，但是缩放与鼠标拖动功能一并消失
            // primaryStage.initStyle(StageStyle.TRANSPARENT);

            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void login() throws Exception {
        // 登录事件
        boolean canLogin = true;
        String IDText = ID.getText();  // 账号数据
        String PasswordText = password.getText();  // 密码数据

        if (ID.getText().isEmpty() || password.getText().isEmpty()) {
            //判空输入
            Alert alert = new Alert(Alert.AlertType.INFORMATION,
                    "输入不能为空！",
                    new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
        } else {
            File file = new File("src/Passwords/" + IDText + ".txt");
            if (file.exists()) {
                //匹配账号密码
                FileReader fr = new FileReader("src/Passwords/" + IDText + ".txt");
                BufferedReader bufferedreader = new BufferedReader(fr);
                String UserPassword = bufferedreader.readLine();
                fr.close();
                if (UserPassword.equals(PasswordText)) {
                    // 登录成功
                    // 反序列IDText.ser获得用户对象
                    UserInfo User = null;
                    try {
                        FileInputStream fileIn = new FileInputStream("src/UserPosts/userObjects/" + IDText + ".ser");
                        ObjectInputStream in = new ObjectInputStream(fileIn);
                        User = (UserInfo) in.readObject();
                        in.close();
                        fileIn.close();
                    } catch (IOException i) {
                        i.printStackTrace();
                    }
                    // 序列化用户对象存入currentUser.ser
                    try {
                        FileOutputStream fileOut =
                                new FileOutputStream("src/UserPosts/currentUser.ser");
                        ObjectOutputStream out = new ObjectOutputStream(fileOut);
                        out.writeObject(User);
                        out.close();
                        fileOut.close();
                    } catch (IOException i) {
                        i.printStackTrace();
                    }

                    String IDHistory_path = "src/Passwords/UserIDHistory.txt";
                    //清空UserIDHistory
                    FileOutputStream clearIDHistory = new FileOutputStream(IDHistory_path);
                    clearIDHistory.write(new String("").getBytes());
                    //重写账号记录
                    File UIDFile = new File(IDHistory_path);
                    FileWriter FW = new FileWriter(UIDFile, true);
                    BufferedWriter writeLoginHistory = new BufferedWriter(FW);
                    writeLoginHistory.write(IDText);
                    writeLoginHistory.flush();
                    writeLoginHistory.close();
                    FW.close();

                    if (rememberPassword.isSelected()) {
                        // 记住密码
                        String PasswordHistory_path = "src/Passwords/UserPasswordHistory.txt";
                        //清空UserPasswordHistory
                        FileOutputStream clearPasswordHistory = new FileOutputStream(PasswordHistory_path);
                        clearPasswordHistory.write(new String("").getBytes());
                        //重写密码记录
                        File PasswordFile = new File(PasswordHistory_path);
                        FileWriter fw = new FileWriter(PasswordFile, true);
                        BufferedWriter writePasswordHistory = new BufferedWriter(fw);
                        writePasswordHistory.write(PasswordText);
                        writePasswordHistory.flush();
                        writePasswordHistory.close();
                        fw.close();
                    } else {
                        // 没记住密码
                        String PasswordHistory_path = "src/Passwords/UserPasswordHistory.txt";
                        //清空UserPasswordHistory
                        FileOutputStream clearPasswordHistory = new FileOutputStream(PasswordHistory_path);
                        clearPasswordHistory.write(new String("").getBytes());
                    }
                    // 登陆成功，打开首页
                    PageSiteController PageSite = new PageSiteController();
                    try {
                        PageSite.start(new Stage());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Stage stage = (Stage) Login_fxml.getScene().getWindow();
                    stage.close();
                } else {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION,
                            "密码输入有误！",
                            new ButtonType("确定", ButtonBar.ButtonData.YES));
                    alert.setHeaderText(null);
                    alert.setTitle("提示");
                    alert.show();
                }
            } else {
                Alert alert = new Alert(Alert.AlertType.INFORMATION,
                        "账号不存在！",
                        new ButtonType("确定", ButtonBar.ButtonData.YES));
                alert.setHeaderText(null);
                alert.setTitle("提示");
                alert.show();
            }
        }
    }

    public void signUp() {
        // 注册账号按钮事件
        SignUpController SignUp = new SignUpController();
        try {
            SignUp.start(new Stage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}